import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'app/routes/app_pages.dart';
import 'app/theme/colors.dart';
import 'app/translations/app_translations.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  // 创建一个 Connectivity 实例用于检查网络连接状态
  final Connectivity _connectivity = Connectivity();
  // 存储当前的网络连接状态，初始值为无网络
  List<ConnectivityResult> _connectionStatus = [ConnectivityResult.none];
  // 声明一个 StreamSubscription 用于监听网络状态变化
  late StreamSubscription<List<ConnectivityResult>> _subscription;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // 订阅网络状态变化
    _subscription = _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
    setupRefreshConfig();
  }

  @override
  void dispose() {
    _subscription.cancel();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
      // 处在不活动状态，无法处理用户响应
        debugPrint("处在不活动状态，无法处理用户响应");
        break;

      case AppLifecycleState.resumed:
        debugPrint("应用程序前台可见，且能响应用户的输入");
        // UmengPushManager.reduceBadge();
        // UmengPushManager.clearBadge();
        // AppLaunching.checkAppVersionUpdate();
        break;

      case AppLifecycleState.paused:
      // 应用程序不可见，不能响应用户的输入，且在后台继续活动中
        debugPrint("应用程序不可见，不能响应用户的输入，且在后台继续活动中");
        // localStorageWrite("native_auth", false);
        // 通知
        // 如果在switch时选择界面，将会丢失上次的界面。只有添加最顶层视图遮盖
        // Get.back();.emit('local_auth_page');
        break;

      case AppLifecycleState.detached:
        break;
      case AppLifecycleState.hidden: // flutter 3.13
        break;
    }
  }

  // 网络监听变化
  Future<void> initConnectivity() async {
    late List<ConnectivityResult> result = [];
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      debugPrint('Couldn\'t check connectivity status = ${e.toString()}',);
      return;
    }
    if (!mounted) {
      return Future.value(null);
    }

    _connectionStatus = result;
    return _updateConnectionStatus(result);
  }

  /// 网络监听回调
  Future<void> _updateConnectionStatus(List<ConnectivityResult> result) async {
    print('当前网络 Connectivity changed: $_connectionStatus');
    switch (result.first) {
      case ConnectivityResult.wifi:
        debugPrint('****** 当前网络 ******');
        debugPrint('****** WIFI ******');
        debugPrint('****** 当前网络 ******');
        break;
      case ConnectivityResult.mobile:
        debugPrint('****** 当前网络 ******');
        debugPrint('****** MOBILE ******');
        debugPrint('****** 当前网络 ******');
        break;
      case ConnectivityResult.none:
      // showMessage('无网络，请检查网络设置');
        break;
      default:
      // showMessage('网络连接失败，请检查网络！');
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      minTextAdapt: true,
      splitScreenMode: true,
      designSize: const Size(375, 812),
      child: GetMaterialApp(
        initialRoute: AppPages.INITIAL,
        getPages: AppPages.routes,
        // locale: Get.deviceLocale,
        debugShowCheckedModeBanner: false,
        // supportedLocales: AppTranslations.supportedLocales,
        // localizationsDelegates: const [
        //   GlobalMaterialLocalizations.delegate, // 指定本地化的字符串和一些其他的值
        //   GlobalCupertinoLocalizations.delegate, // 对应的Cupertino风格
        //   GlobalWidgetsLocalizations.delegate // 指定默认的文本排列方向, 由左到右或由右到左
        // ],
        // localizationsDelegates: FlutterLocalization.instance.localizationsDelegates,
        navigatorObservers: [FlutterSmartDialog.observer],
        builder: FlutterSmartDialog.init(),
        // initialBinding: BindingsController(),
        theme: ThemeData(
          // 设置全局主题
          canvasColor: Colors.transparent, // 为所有 Material 小部件设置默认颜色
          cardColor: Colors.white, //设置卡片颜色
          // brightness: Brightness.dark,
          splashColor: Colors.black12, // 设置触摸水波纹效果的颜色
          highlightColor: Colors.greenAccent, // 设置触摸高亮效果的颜色
          // canvasColor: Colors.white, // 设置画布颜色
          // primaryColor: Colors.white, // 主要颜色
          // primarySwatch: , // 主要颜色样本
          scaffoldBackgroundColor: PageBackgroundColor, //页面背景色
          dialogBackgroundColor: Colors.white,
          shadowColor: Colors.transparent, // 阴影的颜色
          // buttonTheme: const ButtonThemeData(
          //   buttonColor: Colors.white,
          //   minWidth: 0, height: 0, padding: EdgeInsets.all(0),
          // ),
          // buttonTheme: const ButtonThemeData(
          //   buttonColor: Colors.white,
          //   disabledColor: Colors.grey,
          //   focusColor: Colors.white,
          //   hoverColor: Colors.white,
          //   highlightColor: Colors.white,
          //   splashColor: Colors.white,
          // ),
          bottomSheetTheme: const BottomSheetThemeData(
            surfaceTintColor: Colors.transparent,
          ),
          elevatedButtonTheme: ElevatedButtonThemeData(
            style: ElevatedButton.styleFrom(
              // foregroundColor: ThemeColor,
              backgroundColor: Colors.white,
              shadowColor: Colors.transparent,
              surfaceTintColor: Colors.transparent,
              //disabledBackgroundColor: Colors.white,
              //disabledForegroundColor: Colors.amber,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
            ),
          ),
          dialogTheme: const DialogTheme(
            backgroundColor: Colors.white, // 设置对话框的背景颜色为白色
            surfaceTintColor: Colors.white,
            shadowColor: Colors.white,
          ),
          appBarTheme: const AppBarTheme(
            color: ThemeColor,
            toolbarHeight: 44,
            iconTheme: IconThemeData(color: Colors.white),
            elevation: 0,//隐藏底部阴影分割线
            centerTitle: true,//标题是否居中 安卓上有效ios默认居中
            foregroundColor: Colors.white, /// 影响导航标题颜色,
            surfaceTintColor: Colors.white,
          ),
          // textTheme: const TextTheme(
          //
          //   bodySmall: TextStyle(color: Colors.black, fontSize: 18, decoration: TextDecoration.none),
          // ),


          // onGenerateRoute: onGenerateRoute,
          // builder: FlutterSmartDialog.init(),
          // builder: (context, child) {
          //   return GestureDetector(
          //     // 全局添加点击空白处隐藏键盘
          //     onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
          //     child: child,
          //   );
          // },

          // bottomAppBarTheme: const BottomAppBarTheme(
          //   color: Colors.red,//APP_MainViewColor
          // ),


        ),
      ),
    );
  }



  setupRefreshConfig() {
    EasyRefresh.defaultHeaderBuilder = () => const ClassicHeader(
      dragText: "下拉刷新",
      armedText: "松开立即刷新",
      readyText: "刷新中...",
      processingText: "刷新中...",
      processedText: "刷新成功",
      noMoreText: "没有更多",
      failedText: "刷新失败",
      messageText: "最后更新于 %T",
      // dragText: 'Pull to refresh'.tr,
      // armedText: 'Release ready'.tr,
      // readyText: 'Refreshing...'.tr,
      // processingText: 'Refreshing...'.tr,
      // processedText: 'Succeeded'.tr,
      // noMoreText: 'No more'.tr,
      // failedText: 'Failed'.tr,
      // messageText: 'Last updated at %T'.tr,
    );
    EasyRefresh.defaultFooterBuilder = () => const ClassicFooter(
      dragText: "上拉刷新",
      armedText: "松开立即刷新",
      readyText: "刷新中...",
      processingText: "刷新中...",
      processedText: "刷新成功",
      noMoreText: "没有更多",
      failedText: "刷新失败",
      messageText: "最后更新于 %T",
      // dragText: 'Pull to load'.tr,
      // armedText: 'Release ready'.tr,
      // readyText: 'Loading...'.tr,
      // processingText: 'Loading...'.tr,
      // processedText: 'Succeeded'.tr,
      // noMoreText: 'No more'.tr,
      // failedText: 'Failed'.tr,
      // messageText: 'Last updated at %T'.tr,
    );
  }
}

